package com.gopay.scheduler.service.cacert.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.gopay.common.cipher.utils.SensitiveInfoUtils;
import com.gopay.scheduler.dao.CorpMsgSignCertDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.gopay.common.constants.cust.CustCaCertConstants;
import com.gopay.common.constants.cust.MsgSignCertConstants;
import com.gopay.common.cps.dao.acct.CommonQueryDAO;
import com.gopay.common.domain.cert.CorpMsgSignCert;
import com.gopay.common.domain.mail.Send;
import com.gopay.common.exception.GopayException;
import com.gopay.common.security.apicert.dao.CorpMsgSignCertQueryDAO;
import com.gopay.common.util.DateUtils;
import com.gopay.cron.web.util.RemoteServiceUtil;
import com.gopay.remote.cps.mail.MailRemoteService;
import com.gopay.scheduler.service.cacert.CorpMsgSignCertService;

/**
 * 
 * @ClassName: CorpMsgSignCertServiceImpl 
 * @Description: 服务器签名证书service实现
 * @author zhoutong 
 * @date 2016年9月13日 下午4:13:53
 */
@Service("corpMsgSignCertService")
public class CorpMsgSignCertServiceImpl implements CorpMsgSignCertService {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    private @Value("#{webProperties['remotenotify.cps.mail.url']}") String notifyEmailUrl;
    
    @Resource(name = "corpMsgSignCertQueryDAO")
    private CorpMsgSignCertQueryDAO corpMsgSignCertQueryDAO;
    
    @Resource(name = "comQueryDao")
    private CommonQueryDAO commonDao;

    @Resource(name = "corpMsgSignCertDAO")
    private CorpMsgSignCertDAO corpMsgSignCertDAO;

    /**
     * 
     * @Description: 通过客户号、状态查询服务器签名证书列表
     * @param stat currentDate limitDate
     * @return 
     * @author zhuliang
     */
    public List<CorpMsgSignCert> getCorpMsgSignCertList() {
        
//        String hql="FROM ReportConsoleBalanceQuery WHERE acctTs=TO_DATE(:acctTs, 'YYYYMMDD') and acctId=:acctId";
//        
        String hql = "from CorpMsgSignCert where 1=1 "
                + " and stat!=:stat"
                + " and VALID_TO>=TO_DATE(:currentDate,'yyyy-MM-dd')"
                + " and VALID_TO<=TO_DATE(:limitDate,'yyyy-MM-dd') ";
        Map<String, Object> param = new HashMap<>();
        String dateFormat="yyyy-MM-dd";
        
        Date curDate = DateUtils.getSystemDate();//当前时间
        //获取当前日期的后三个月时间
        Date compDate = DateUtils.add(curDate, Calendar.MONTH, MsgSignCertConstants.CORP_MSG_SIGN_CERT_VALID_LIMIT);//用于进行对比的时间
        String currentDate=DateUtils.format(curDate,dateFormat);
        String limitDate=DateUtils.format(compDate,dateFormat);

        param.put("stat",  MsgSignCertConstants.CORP_MSG_SIGN_CERT_STAT_INVALID);//有效和更换审核中的都查询出来
        param.put("currentDate",currentDate);
        param.put("limitDate",limitDate );
        logger.info("服务器签名证书到期提醒查询语句为：" + hql.toString());
        List<CorpMsgSignCert> list = corpMsgSignCertQueryDAO.findByHql(hql.toString(), param);

        return list;
    }

    /**
     * 构建查询sq
     * 
     * @return
     */
    private String buildSql() {
        
        
        StringBuilder sql = new StringBuilder();
        String dateFormat="yyyy-MM-dd";
        
        Date curDate = DateUtils.getSystemDate();//当前时间
        // 获取当前日期的后三个月时间
        Date compDate = DateUtils.add(curDate, Calendar.MONTH, MsgSignCertConstants.CORP_MSG_SIGN_CERT_VALID_LIMIT);//用于进行对比的时间
        
        String currentDate=DateUtils.format(curDate,dateFormat);
        String limitDate=DateUtils.format(compDate,dateFormat);

        sql.append("select ");
        sql.append("c.cust_id,");
        sql.append("c.cert_alias, ");
        sql.append("c.cert_email,");
        sql.append("c.valid_to ");
        sql.append("from corp_msg_sign_cert c ");
        
        // where
        sql.append(" where 1=1 ");
        sql.append(" and c.stat= '11'");
        sql.append(" and VALID_TO >= TO_DATE('" + currentDate + "', 'YYYY-MM-DD') ");
        sql.append(" and VALID_TO <= TO_DATE('" + limitDate + "', 'YYYY-MM-DD') ");
        logger.info("查询语句为：" + sql);
        return sql.toString();
    }

    @Override
    public void sendMail(Send send) {
        try {
            MailRemoteService mailRemoteService = this.getMailRemoteService();
            mailRemoteService.addMailTask(send);
        } catch (GopayException e) {
            logger.error("发送邮件异常：", e);
        }

    }
    
    private MailRemoteService getMailRemoteService() throws GopayException {
        MailRemoteService service = null;
        service = (MailRemoteService) RemoteServiceUtil.getRemoteService(MailRemoteService.class, notifyEmailUrl);
        return service;
    }

    @Override
    public List<CorpMsgSignCert> getDataToEnc() {
        String hql = "from CorpMsgSignCert t where 1=1 and t.privateKeyPCI IS NULL ";
        Map<String, Object> param = new HashMap<>();
        List<CorpMsgSignCert> list = corpMsgSignCertQueryDAO.findByHql(hql.toString(), param);
        return list;
    }

    @Override
    public void updateEncData(CorpMsgSignCert corpMsgSignCert){
       /* String sql ="update CORP_MSG_SIGN_CERT set CERT_SIGN_BUF_PCI=:certSignBufPCI, PRIVATE_KEY_PCI=:privateKeyPCI, PFXCERT_PCI=:pfxCertPCI where ID=:id ";
        Map<String, Object> param = new HashMap<>();
        param.put("privateKeyPCI",SensitiveInfoUtils.smartEncryptWithCheck(corpMsgSignCert.getPrivateKey()));
        param.put("certSignBufPCI",SensitiveInfoUtils.smartEncryptWithCheck(corpMsgSignCert.getCertSignBuf()));
        param.put("pfxCertPCI",SensitiveInfoUtils.smartEncryptWithCheck(corpMsgSignCert.getPfxCert()));
        param.put("id",corpMsgSignCert.getId());
        corpMsgSignCertDAO.updateBySql(sql,param);*/

        corpMsgSignCertDAO.update(corpMsgSignCert);
    }
}
